﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using MyK3CloudCore.IOC.Extensions;
using System;
using System.Linq;
using System.Net.Http;

namespace MyK3CloudCore.IOC;

public class K3Services
{
    public static void AddK3Sugar(K3Config config)
    {
        K3IOCServiceCollectionExtensions.Configs = config;
        var server = new ServiceCollection();
        server.AddDefaultHttpClient(K3IOCServiceCollectionExtensions._cookie);
        K3IOCServiceCollectionExtensions.HttpClientFactory = server.BuildServiceProvider().GetService<IHttpClientFactory>();
    }
    public static void AddK3Sugar(Action<K3Config> setupAction)
    {
        K3Config k3Config = new();
        setupAction?.Invoke(k3Config);
        AddK3Sugar(k3Config);
    }
    public static void AddK3Sugar()
    {
        var builder = new ConfigurationBuilder().AddInMemoryCollection().AddJsonFile("appsettings.json", false).Build();
        var k3CloudConfit = builder.GetSection("K3CLOUDCONFIG");
        if (k3CloudConfit == null) { throw new ArgumentNullException(nameof(k3CloudConfit)); }
        var k3Config = builder.GetValue<K3Config>("K3CLOUDCONFIG");
        if (k3Config == null)
        {
            var children = builder.GetSection("K3CLOUDCONFIG").GetChildren();
            k3Config = children.First().Get<K3Config>();
        }
        AddK3Sugar(k3Config);
    }
}
